/**
 * 
 */
package com.thinkgsp.jxc.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgsp.jxc.model.Dept;
import com.thinkgsp.jxc.persistence.DeptMapper;
import com.thinkgsp.jxc.service.DeptService;
import com.thinkgsp.jxc.service.ModelExistsException;
import com.thinkgsp.sys.persistence.PersistenceException;

/**
 * DeptService 的实现类
 * @author evan
 *
 */
@Service("deptService")
@Transactional
public class DeptServiceImpl extends GeneralServiceImpl implements DeptService {

	
	@Autowired
	private DeptMapper deptMapper;
	
	/**
	 * 设置DeptMapper,本方法用于测试目的
	 * @param deptMapper
	 */
	public void setDeptMapper(DeptMapper deptMapper) {
		this.deptMapper = deptMapper;
	}
	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.DeptService#getDept(java.lang.Integer)
	 */
	public Dept getDept(Integer deptId) {
		return deptMapper.getDept(deptId);
	}

	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.DeptService#getAllDept()
	 */
	public List<Dept> getAllDept() {
		return deptMapper.getAllDept();
	}

	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.DeptService#saveDept(com.thinkgsp.jxc.model.Dept)
	 */
	public void saveDept(Dept dept) throws ModelExistsException,PersistenceException {
		try {
			if(dept.getDeptId() == null || dept.getDeptId().intValue() == 0) {
				deptMapper.insertDept(dept);
			} else {
				deptMapper.updateDept(dept);
			}
		} catch(DuplicateKeyException e) {
			log.warn(e.getMessage());
			throw new ModelExistsException("部门:'" + dept.getDeptName() + "' 已经存在。");
		} catch(Exception e) {
			log.error(e);
			throw new PersistenceException("部门:'" + dept.getDeptName() + "' 保存失败。");
		}

	}

	/* (non-Javadoc)
	 * @see com.thinkgsp.jxc.service.DeptService#deleteDept(java.lang.Integer)
	 */
	public void deleteDept(Integer deptId) throws PersistenceException {
		int cnt = deptMapper.deleteDept(deptId);
		if(cnt == 0) {
			log.warn("Delete dept by id :'" + deptId + "' faild.");
			throw new PersistenceException("部门:'" + deptId + "' 删除失败。");
		}
	}

}
